package com.zero.activemq;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;


public class JMSQueueConsumer {

    public static void main(String[] args) {
        ConnectionFactory connectionFactory= new ActiveMQConnectionFactory("tcp://192.168.0.50:61616?jms.optimizeAcknowledge=true&jms.optimizeAcknowledgeTimeOut=10000");
        Connection connection=null;
        try {

            connection=connectionFactory.createConnection();
            connection.start();

            Session session=connection.createSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE); //延迟确认
            //创建目的地
            Destination destination=session.createQueue("myQueue?consumer.prefetchSize=5");
            //创建发送者
            MessageConsumer consumer=session.createConsumer(destination);
            for(int i=0; i<10; i++) {
                TextMessage textMessage = (TextMessage) consumer.receive();
                //在接收端接收
                String stringProperty = textMessage.getStringProperty("wql");

                String messageID = textMessage.getJMSMessageID();

                System.out.println("property:"+ stringProperty+",messageID:"+messageID+","+textMessage.getText());

                Thread.sleep(1000);
            }
            session.commit();//表示消息被自动确认
            session.close();
        } catch (JMSException | InterruptedException e) {
            e.printStackTrace();
        }finally {
            if(connection!=null){
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
